/**
 * User: aOmMiez
 * Date: 3/25/13 AD
 * Time: 1:40 PM
 * NodeJs Core Server
 */

var config = require(__dirname+'/config.js');
var express = require('express');
GLOBAL.Exception = require(__dirname+'/exception/Exception.js');
GLOBAL.components = {};
GLOBAL.basePath = __dirname;
GLOBAL.components.string = require(__dirname+'/components/string.js');
GLOBAL.Services = require(__dirname+'/components/Services.js');
GLOBAL.App = express();
GLOBAL.App.use(express.bodyParser({ keepExtensions: true })); // Required for parsing POST

var mongo = require('mongodb');
var fs = require('fs');

var mysqll = require("mysql");

components.mongo = new mongo.Db(config.mongo.db, new mongo.Server(config.mongo.host, config.mongo.port, {auto_reconnect : true }), {});

// Setup Mysql
GLOBAL.Mysql = mysqll.createConnection(config.mysql);

function handleDisconnect(connection) {
    connection.on('error', function(err) {
        if (!err.fatal) {
            return;
        }

        if (err.code !== 'PROTOCOL_CONNECTION_LOST') {
            throw err;
        }

        console.log('Re-connecting lost connection: ' + err.stack);

        connection = mysqll.createConnection(connection.config);
        handleDisconnect(connection);
        connection.connect();
        GLOBAL.mysql = connection;
    });
}
handleDisconnect(GLOBAL.Mysql);

GLOBAL.Mysql.connect(function(error, results) {
    if(error) {
        console.log('Connection Error: ' + error.message);
        return;
    }
    GLOBAL.Mysql.query('USE '+config.mysql.db);
    console.log('Connected to MySQL');
});

process.on('uncaughtException', function(ex) {
	if(ex instanceof Exception) {
		ex.printConsole();
		ex.callback();
	}
	else{
		console.log(ex);
	}
});

require(__dirname+'/routes/routes.js');